<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Santri extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('flexigrid');
        $this->load->library('form_validation');
        $this->load->helper('flexigrid');
        $this->load->helper(array('form', 'url'));
        $this->load->model('santri_model');
		$this->load->model('periode_model');
    }

    //load Grid
    function index() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $colModel['no'] = array('No', 30, TRUE, 'center', 0);
            $colModel['Nama_Santri'] = array('Nama Santri', 250, TRUE, 'center', 1);
            $colModel['Munakosah'] = array('No Induk', 150, TRUE, 'center', 1);
            $colModel['Asal_Santri'] = array('Alamat', 250, TRUE, 'center', 1);
            $colModel['Edit'] = array('Edit', 30, TRUE, 'center', 0);
			$colModel['Detail_Santri'] = array('Detail Santri', 70, TRUE, 'center', 0);
			$colModel['Detail_Kursus'] = array('Detail Kursus', 70, TRUE, 'center', 0);

            $gridParams = array(
                'width' => 'auto',
                'height' => 300,
                'rp' => 10,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
                'title' => 'Daftar Santri',
                'showTableToggleBtn' => true
            );

            $buttons[] = array('tambah', 'add', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('hapus', 'delete', 'spt_js');


            // mengambil data dari file controler ajax pada method grid_foto
            $grid_js = build_grid_js('flex1', site_url("santri/grid_foto"), $colModel, 'Nama_Santri', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
        function spt_js(com,grid)
        {
                if (com=='tambah')
                {
                        location.href='" . base_url() . "index.php/santri/form';
                }

                if (com=='hapus')
                        {
                           if($('.trSelected',grid).length>0){
                                   if(confirm('Anda yakin menghapus ' + $('.trSelected',grid).length + ' santri?')){
                                                var items = $('.trSelected',grid);
                                                var itemlist ='';
                                                for(i=0;i<items.length;i++){
                                                        itemlist+= items[i].id.substr(3)+',';
                                                }
                                                $.ajax({
                                                   type: 'POST',
                                                   url: '" . base_url() . "index.php/santri/delete" . "',
                                                   data: 'items='+itemlist,
                                                   success: function(data){
                                                        $('#flex1').flexReload();
														alert(data);
                                                   }
                                                });
                                        }
                                } else {
                                        return false;
                                }
                        }

        }
        </script>
        ";


            $data['js_grid'] = $grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid_foto() {
        $valid_fields = array('Nama_Santri', 'Munakosah', 'Asal_Santri', 'Email_Santri');
        $this->flexigrid->validate_post('Nama_Santri', 'asc', $valid_fields);
		$records = $this->santri_model->get_data_santri();
		//$records = str_replace("\'", "'", $records);
		$this->output->set_header($this->config->item('json_header'));
        $no = 0;
		
        foreach ($records['records']->result() as $row) {
            $status_aktif = "";
            // $lokasi_foto = base_url() . $row->foto_santri;
            $new_tab = 'target="_blank"';
			$nama_santri = str_replace("\'", "'", $row->nama_santri);
            $record_items[] = array(
                $row->id_santri,
                $no = $no + 1,
                //'<a href= \'' . $lokasi_foto . '\' ' . $new_tab . '><img border=\'0\' src=\'' . $lokasi_foto . '\' height=\'50\'></a> ',
                $nama_santri,
                $row->munakosah,
                $row->asal_santri,
                '<a href=\'' . base_url() . 'index.php/santri/edit/' . $row->id_santri . '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/edit.png\'></a> ',
				'<a href=\'' . base_url() . 'index.php/santri/detail_santri/' . $row->id_santri. '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/page.png\'></a> ',
				'<a href=\'' . base_url() . 'index.php/detail_kursus/index/' . $row->id_santri. '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/folder.png\'></a> ',
				
            );
			
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }

    function form() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
					//get date
					$y = date("y");
					$m = date("m");
					
					//get active_period
					$aktif = $this->periode_model->active_period();
					
					foreach ($aktif as $row){	
						$period=$row->NAMA_PERIODE;
					}
					
					$awal = $period.'01120001';
					$akhir = $period+'1'.'01120001';
					
					//cek data yang sama
					$sql = $this->db->query("SELECT COUNT(munakosah) AS CEK FROM santri WHERE munakosah > ".$awal." AND munakosah < ".$akhir."");
					$cek = '';
										
					foreach ($sql->result() as $rows) {
						$cek = $rows->CEK;
					}
										
					if ($cek > 0) {
						//cari munakosah tertinggi dalam satu periode
						$sql2 = $this->db->query("SELECT munakosah FROM santri WHERE munakosah > ".$awal." AND munakosah < ".$akhir."");
						$counter = 0;
						foreach ($sql2->result() as $rows) {
							$cek2[$counter] = $rows->munakosah;
							$counter++;
						}
						$max_muna = max($cek2);
					
						$saiki = substr($max_muna, -4);
						$number = $period.$y.$m.$saiki+1;
					}
					else{
						$number = $period.$y.$m.'0001';
					}
				
            $data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
			$data['munakosah'] = $number;
            $data['content'] = $this->load->view('form_santri', $data, true);
            $this->load->view('main', $data);
        }
    }

    function upload() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            if ($this->cek_validasi() == FALSE) {
                $this->form();
            } else {
                $field_name = 'foto_santri';
                $config['upload_path'] = "gallery/santri";
                $config['allowed_types'] = '*';
				
				//create folder
				if(!is_dir($config['upload_path'])){
					mkdir($config['upload_path'], 0777);
					//mkdir($config['upload_path2'], 0777);
				}
			
                $this->load->library('upload', $config);
                $files = $this->upload->do_upload($field_name);

                    $data = $this->upload->data($field_name); //get file_name
                    
					if (!$files) {
						$file_name = 'default.jpg';
						}
					else {
						$file_name = $data['file_name'];
						}					
					
                    $path[0] = 'gallery/santri/' . $file_name;
                    $path[1] = $file_name;
                    //return $path;
					//$nomor = $this->santri_model->get_munakosah();
									
					//get max_munakosah
					// $nilai = $this->santri_model->get_munakosah2();
					// $a=0;
					// foreach ($nilai as $row){
						// $datadata[$a]=$row->munakosah;
						// $a++;
					// }
					// $max = max($datadata);
					
					//get max_period
					// $nilai_p = $this->periode_model->get_period();
					// $p=0;
					// foreach ($nilai_p as $row){
						// $data_p[$p]=$row->NAMA_PERIODE;
						// $p++;
					// }
					// $max_p = max($data_p);
													
					//get date
					$y = date("y");
					$m = date("m");
					
					//get active_period
					$aktif = $this->periode_model->active_period();
					
					foreach ($aktif as $row){	
						$period=$row->NAMA_PERIODE;
					}
					
					$awal = $period.'01120001';
					$akhir = $period+'1'.'01120001';
					
					//cek data yang sama
					$sql = $this->db->query("SELECT COUNT(munakosah) AS CEK FROM santri WHERE munakosah > ".$awal." AND munakosah < ".$akhir."");
					$cek = '';
										
					foreach ($sql->result() as $rows) {
						$cek = $rows->CEK;
					}
										
					if ($cek > 0) {
						//cari munakosah tertinggi dalam satu periode
						$sql2 = $this->db->query("SELECT munakosah FROM santri WHERE munakosah > ".$awal." AND munakosah < ".$akhir."");
						$counter = 0;
						foreach ($sql2->result() as $rows) {
							$cek2[$counter] = $rows->munakosah;
							$counter++;
						}
						$max_muna = max($cek2);
					
						$saiki = substr($max_muna, -4);
						$number = $period.$y.$m.$saiki+1;
					}
					else{
						$number = $period.$y.$m.'0001';
					}		
					
					$data = array(
                        'NAMA_SANTRI' => $this->input->post('nama_santri'),
                        'MUNAKOSAH' => $number,
                        'ASAL_SANTRI' => $this->input->post('asal_santri'),
                        'KECAMATAN' => $this->input->post('kecamatan'),
                        'KOTA' => $this->input->post('kota'),
                        'TELPON_SANTRI' => $this->input->post('telpon_santri'),
						'TEMPAT_LAHIR' => $this->input->post('tempat_lahir'),
						'TANGGAL_LAHIR' => $this->input->post('tanggal_lahir'),
						'ID_JK' => $this->input->post('id_jk'),
						'ID_STATUS' => $this->input->post('id_status'),
						'ID_PENDIDIKAN' => $this->input->post('id_pendidikan'),
						'PEKERJAAN_SANTRI' => $this->input->post('pekerjaan_santri'),
						'INSTANSI' => $this->input->post('instansi'),
						'JABATAN' => $this->input->post('jabatan'),
						'ALAMAT_PERUSAHAAN' => $this->input->post('alamat_perusahaan'),
                        'TANGGAL_PENDAFTARAN' => date('Y-m-d'),
						'FOTO_SANTRI' => $path[0]
                    );
					$data = str_replace("'", "\'", $data);
                    $this->santri_model->insert($data);
					
					//get data for redirect to kursus santri
					//$id_santri = "";
					$nohp = $this->input->post('telpon_santri');
					$hasil_id = $this->santri_model->get_id_santri($number, $nohp);
					foreach ($hasil_id->result() as $row){
						$id_santri = $row->id_santri;
					}
					redirect('detail_kursus/index/'.$id_santri.'');
			
                }
            }
        }
    

    public function edit($id) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $data['status'] = 'edit';
            $record_artikel = $this->santri_model->selectone($id);
            foreach ($record_artikel->result() as $artikel) {
                $data['id_santri'] = $artikel->id_santri;
                $data['nama_santri'] = $artikel->nama_santri;
                $data['munakosah'] = $artikel->munakosah;
                $data['asal_santri'] = $artikel->asal_santri;
                $data['kecamatan'] = $artikel->kecamatan;
                $data['kota'] = $artikel->kota;
                $data['telpon_santri'] = $artikel->telpon_santri;
                $data['tempat_lahir'] = $artikel->tempat_lahir;
                $data['tanggal_lahir'] = $artikel->tanggal_lahir;
				$data['id_jk'] = $artikel->id_jk;
				$data['id_status'] = $artikel->id_status;
				$data['id_pendidikan'] = $artikel->id_pendidikan;
				$data['pekerjaan_santri'] = $artikel->pekerjaan_santri;
				$data['instansi'] = $artikel->instansi;
				$data['jabatan'] = $artikel->jabatan;
				$data['alamat_perusahaan'] = $artikel->alamat_perusahaan;
                $data['tanggal_pendaftaran'] = $artikel->tanggal_pendaftaran;
				$data['foto_santri'] = base_url() . $artikel->foto_santri;
            }
            //$data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
			$data = str_replace("\'", "'", $data);
            $data['santri'] = $this->santri_model->get_data_all_santri();
			$data['content'] = $this->load->view('form_santri', $data, true);
            $this->load->view('main', $data);
        }
    }

    function update($id) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            if ($this->cek_validasi() == FALSE) {
                $this->edit($id);
            } else {
                $field_name = 'foto_santri';
                $config['upload_path'] = "gallery/santri";
                $config['allowed_types'] = '*';
				
				//create folder
				if(!is_dir($config['upload_path'])){
					mkdir($config['upload_path'], 0777);
					//mkdir($config['upload_path2'], 0777);
				}
                
                $this->load->library('upload', $config);
                $files = $this->upload->do_upload($field_name);
                $file_name = '';

                if (!$files) {
                    $data = $this->upload->data($field_name); //get file_name
                    $file_name = $data['file_name'];
                    $path[0] = 'gallery/santri/' . $file_name;
                    $path[1] = $file_name;
					
														
					$data = array(
                        'NAMA_SANTRI' => $this->input->post("nama_santri"),
                     
                        'ASAL_SANTRI' => $this->input->post('asal_santri'),
						'KECAMATAN' => $this->input->post('kecamatan'),
                        'KOTA' => $this->input->post('kota'),
                        'TELPON_SANTRI' => $this->input->post('telpon_santri'),
						'TEMPAT_LAHIR' => $this->input->post('tempat_lahir'),
						'TANGGAL_LAHIR' => $this->input->post('tanggal_lahir'),
						'ID_JK' => $this->input->post('id_jk'),
						'ID_STATUS' => $this->input->post('id_status'),
						'ID_PENDIDIKAN' => $this->input->post('id_pendidikan'),
						'PEKERJAAN_SANTRI' => $this->input->post('pekerjaan_santri'),
						'INSTANSI' => $this->input->post('instansi'),
						'JABATAN' => $this->input->post('jabatan'),
						'ALAMAT_PERUSAHAAN' => $this->input->post('alamat_perusahaan'),
                        'TANGGAL_PENDAFTARAN' => $this->input->post('tanggal_pendaftaran')
						);
					$data = str_replace("'", "\'", $data);
                    $this->santri_model->update($id, $data);
                    redirect('detail_kursus/index/'.$id.'');
					//redirect('santri');
                } else {
                    $data = $this->upload->data($field_name); //get file_name
                    $file_name = $data['file_name'];
                    $path[0] = 'gallery/santri/' . $file_name;
                    $path[1] = $file_name;
                    
                    $data = array(
                        'NAMA_SANTRI' => $this->input->post("nama_santri"),
                        'ASAL_SANTRI' => $this->input->post('asal_santri'),
						'KECAMATAN' => $this->input->post('kecamatan'),
                        'KOTA' => $this->input->post('kota'),
                        'TELPON_SANTRI' => $this->input->post('telpon_santri'),
						'TEMPAT_LAHIR' => $this->input->post('tempat_lahir'),
						'TANGGAL_LAHIR' => $this->input->post('tanggal_lahir'),
						'ID_JK' => $this->input->post('id_jk'),
						'ID_STATUS' => $this->input->post('id_status'),
						'ID_PENDIDIKAN' => $this->input->post('id_pendidikan'),
						'PEKERJAAN_SANTRI' => $this->input->post('pekerjaan_santri'),
						'INSTANSI' => $this->input->post('instansi'),
						'JABATAN' => $this->input->post('jabatan'),
						'ALAMAT_PERUSAHAAN' => $this->input->post('alamat_perusahaan'),
                        'TANGGAL_PENDAFTARAN' => $this->input->post('tanggal_pendaftaran'),
                        'FOTO_SANTRI' => $path[0]
                    );
					$data = str_replace("'", "\'", $data);
                    $this->santri_model->update($id, $data);
                    redirect('detail_kursus/index/'.$id.'');
					//redirect('santri');
                }
            }
        }
    }
	function detail_santri($id) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $data['status'] = 'detail_santri';
            $record_artikel = $this->santri_model->selectone($id);
            foreach ($record_artikel->result() as $artikel) {
                $data['id_santri'] = $artikel->id_santri;
                $data['nama_santri'] = $artikel->nama_santri;
                $data['munakosah'] = $artikel->munakosah;
                $data['asal_santri'] = $artikel->asal_santri;
                $data['telpon_santri'] = $artikel->telpon_santri;
                $data['tempat_lahir'] = $artikel->tempat_lahir;
                $data['tanggal_lahir'] = $artikel->tanggal_lahir;
				$data['id_jk'] = $artikel->id_jk;
				$data['id_status'] = $artikel->id_status;
				$data['id_pendidikan'] = $artikel->id_pendidikan;
				$data['pekerjaan_santri'] = $artikel->pekerjaan_santri;
				$data['instansi'] = $artikel->instansi;
				$data['jabatan'] = $artikel->jabatan;
				$data['alamat_perusahaan'] = $artikel->alamat_perusahaan;
                $data['tanggal_pendaftaran'] = $artikel->tanggal_pendaftaran;
				$data['foto_santri'] = base_url() . $artikel->foto_santri;
            }
            //$data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
			$data = str_replace("\'", "'", $data);
            $data['santri'] = $this->santri_model->get_data_all_santri();
			$data['content'] = $this->load->view('detail_santri', $data, true);
            $this->load->view('main', $data);
        }
    }

    function delete() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
			$spt_ids_post_array = explode(",", $this->input->post('items'));
            foreach ($spt_ids_post_array as $id_santri)
			{
				//cek data ustad
				if (isset($id_santri) && $id_santri != '') {
					$sql = $this->db->query("SELECT COUNT(id_kelas_santri) AS CEK FROM kelas_santri WHERE id_santri = ".$id_santri."");
					$cek = '';
					foreach ($sql->result() as $rows)
					{
						$cek = $rows->CEK;
					}
							
					$msg='';
					if($cek > 0)
					{
						$msg ='Proses hapus gagal. Data santri masih tergabung dalam kelas.';
					}
					else
					{
						$this->santri_model->delete($id_santri);
						$msg ='Data yang Anda pilih berhasil dihapus.';
					}
					$this->output->set_header($this->config->item('ajax_header'));
					$this->output->set_output($msg);
				}
			}
        }
    }
	
	function alpha_space($str)
    {
        return ( ! preg_match("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ", $str)) ? FALSE : TRUE;
    } 

    function cek_validasi() {
        // Setting Rules
        $this->form_validation->set_rules('nama_santri', 'Nama Santri', 'required');
		$this->form_validation->set_rules('asal_santri', 'Alamat', 'required');
		$this->form_validation->set_rules('telpon_santri', 'Telpon/HP', 'required|numeric|greater_than[0]');
		//$this->form_validation->set_rules('tempat_lahir', 'Tempat Lahir', 'required');
		//$this->form_validation->set_rules('tanggal_lahir', 'Tanggal Lahir', 'required');
		$this->form_validation->set_rules('id_jk', 'Jenis Kelamin', 'required');
		$this->form_validation->set_rules('id_status', 'Status', 'required');
		$this->form_validation->set_rules('id_pendidikan', 'Pendidikan', 'required');
		//$this->form_validation->set_rules('pekerjaan_santri', 'Pekerjaan', 'required');
		
        //Setting Error Message
        $this->form_validation->set_message('required', 'Field %s harus diisi.');
        $this->form_validation->set_message('numeric', 'Field %s harus diisi angka.');
		$this->form_validation->set_message('greater_than', 'Field %s harus diisi angka lebih dari 0');
		//$this->form_validation->set_message('alpha_space', 'Field %s harus diisi dengan huruf dan spasi');
		


        // Setting Delimiter
        $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }

}
